#! /usr/bin/python
# -*- coding:  utf-8 -*-
#
# accoufer : cgi script for creating an offer
# 
# Copyright S.Keim 2011
# Available under the MIT licence see the COPYING file

import accoufer
import shelve
import cgi , math

def run():
    # logged user
    login, user = accoufer.userCookie()

    clients = {}
    rows = []
    for uoffer in user[accoufer.USER_OFFERS]:
        clientref = str(uoffer[accoufer.USER_OFF_CLIENT])
        offers = clients.get(clientref, None)
        if offers is None:
            offers = shelve.open(accoufer.offerpath(clientref), 'w')
            clients[clientref] = offers
        oref = str(uoffer[accoufer.USER_OFF_REF])
        offer = offers[oref]
        svalue, min_svalue, tx = offer[1:4]
        cvalue = math.ceil(svalue*tx)
        min_cvalue =  math.ceil(min_svalue*tx)
        
        r ="<tr><td>%s</td> <td>%s</td> <td>-%s</td> <td>-%s</td><td>+%s</td><td>+%s</td></tr>"%(offers[accoufer.NAME_KEY], tx, min_svalue, svalue,  min_cvalue, cvalue,  )
        rows.append(r)

    # output message
    credits = user[accoufer.USER_CREDITS]
    msg =  PAGE%(login,credits,"<br/>".join(rows))
    print accoufer.HTML%("User offers: "+login, msg)
    
    

PAGE = """
<h1>User offers: %s </h1>
Credits:%s<p/>
<table border=1>
    <tr><th colspan=2></th><th colspan=2>Here</th><th colspan=2>On client</th>
    <tr><th>Client</th><th>tx</th><th>min</th><th>value</th><th>min</th><th>value</th></tr>
    %s
</table>
 <hr/><a href="./index.html">Start</a>"""



ERROR = "<b>%s</b><p/>"


if __name__=="__main__":
    run()

